package nckd.wnqjt.tmc.tda.plugin.form;

import kd.bos.algo.DataSet;
import kd.bos.entity.report.AbstractReportListDataPlugin;
import kd.bos.entity.report.ReportQueryParam;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Date;

/**
 * @author zhujintao
 * @date 2024/11/05
 * @desc 近3个月借款到期情况
 */
public class LoanExpireListDataPlugin extends AbstractReportListDataPlugin {
    /**
     * 取数逻辑：银行借款结束日期-当前时间上月月底日期<3个月，单据数据：银行提款单还款计划
     * 公司：借款人；
     * 金融机构：提款单的债权人；
     * 本金：预计还本金；
     * 到期时间：提款单的到期日期；
     * 还款资金安排：留白；
     * 还款资金安排线上允许编辑文本内容
     *
     * @param reportQueryParam
     * @param o
     * @return
     * @throws Throwable
     */
    @Override
    public DataSet query(ReportQueryParam reportQueryParam, Object o) throws Throwable {
        String selectField = "id,org,textcreditor,repayplan_entry.exrepaymentdate exrepaymentdate,repayplan_entry.exdrawamount exdrawamount";
        //获取当前日期，用于计算3个月的日期
        LocalDate currentDate = LocalDate.now();
        int currentMonth = currentDate.getMonthValue();
        //设置当前日期为上个月的第一天
        int lastMonth = (currentMonth == 1) ? 12 : currentMonth - 1;
        LocalDate firstDayOfLastMonth = currentDate.withMonth(lastMonth).withDayOfMonth(1);
        //获取上个月的最后一天
        LocalDate lastDayOfLastMonth = firstDayOfLastMonth.plusMonths(1).minusDays(1);
        //lastDayOfLastMonth 3个月后的这一天
        LocalDateTime localDateTime = lastDayOfLastMonth.plusMonths(3).atTime(23, 59, 59);
        //格式化日期为所需的格式
        Date startdate = Date.from(lastDayOfLastMonth.atTime(0, 0, 0).atZone(ZoneId.systemDefault()).toInstant());
        Date enddate = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        QFilter filter = new QFilter("loantype", QCP.in, Arrays.asList("loan", "sl"))
                .and("repayplan_entry.exdrawamount", QCP.large_than, 0)
                .and("repayplan_entry.exrepaymentdate", QCP.large_than, startdate)
                .and("repayplan_entry.exrepaymentdate", QCP.less_equals, enddate);
        DataSet dataSet = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cfm_loanbill", selectField, filter.toArray(), null);
        return dataSet;
    }
}